package com.feri.openapi.redis;

/*
 * 基于RedissionRedis数据库
 *
 * */


import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class RedissionUtils {
    private static RedissonClient redisson;
    static {
        //创建配置对象
        Config config = new Config();
        //设置地址、密码、连接池
        //单机，没有集群
        config.useSingleServer().setAddress("redis:10.211.55.3:6379").setPassword("12345678").setConnectionPoolSize(25);
        //实例化客户端对象
        redisson=Redisson.create(config);

    }

    //新增
    public static void setStr(String key,String msg,long seconds) {
        if (seconds > 0) {
            redisson.getBucket(key).set(msg, seconds, TimeUnit.SECONDS);
        }
        redisson.getBucket(key).set(msg);

    }
    //新增hash
    public static void setHash(String key, Map<String,Object> map) {
        redisson.getMap(key).putAll(map);
    }
    //新增list
    public static void setList(String key, List<Object> list) {
        redisson.getList(key).addAll(list);
    }
    //新增set
    public static void setSet(String key, Set<Object> set) {
        redisson.getSet(key).addAll(set);
    }
    //新增Zset中的Double是可以重复的，可以整型也可以是小数
    public static void setZset(String key, Map<Object,Double> map) {
        redisson.getScoredSortedSet(key).addAll(map);
    }
    //删除
    public static void removeStr(String key ) {
        redisson.getKeys().delete(key);
    }
    //删除Hash中的某个元素
    public static void removeHash(String key ,String field) {
        redisson.getMap(key).remove(field);
    }

    //查询字符串
    public static  String getStr(String key){
        return (String) redisson.getBucket(key).get();
    }
    //查询集合
    public static  List<Object> getlist(String key){
        return  redisson.getList(key).readAll();
    }
    //其他

    //设置有效时间
    public static  void expire(String key,long secodes){
        redisson.getKeys().expire(key,secodes,TimeUnit.SECONDS);
    }
    //校验指定的key存在
    public static  boolean checkKey(String key){
        return redisson.getKeys().countExists(key)>0;
    }
    //setnx
    //加锁
    public static RLock lock(String key){
        RLock rLock = redisson.getLock(key);
        return  rLock;
    }
    //解锁
    public static void unlock(RLock lock){
        lock.unlockAsync();//异步的性能高
    }
/*    public static void unlock(RLock lock){
        lock.unlock();
    }*/
}
